package com.moxie.ocr.ocr.utils;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;




/**
 * 自定义Toast：可以任意设定显示时长
 * 使用WindowManager实现悬浮窗的方式
 */
public class MXWindowToast {
    private static final int SHOW = 0;
    private static final int HIDE = 1;

    private WindowManager mWindowManager;
    private View view;
    WindowManager.LayoutParams params;
    private int duration;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW:
                    handler.sendEmptyMessageDelayed(HIDE, duration);
                    break;
                case HIDE:
                    hide();
                    break;
            }
        }
    };

    /**
     * type = TYPE_APPLICATION_OVERLAY
     * 需要权限 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
     * */
    public MXWindowToast makeToast(Context context, String msg, int duration) {
        mWindowManager  = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();
//        params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        params.windowAnimations = android.R.style.Animation_Toast;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.TRANSLUCENT;
        params.width  = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.CENTER;
        view = new TextView(context);
        TextView textView = (TextView) view;
        textView.setText(msg);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(18);

        this.duration = duration;
        return this;
    }

    /**
     * 设置Toast位置
     * */
    public MXWindowToast setGravity(int type){
        params.gravity = type;
        return this;
    }

    /**
     * 设置Toast所在的view样式
     * */
    public MXWindowToast setView(View view) {
        this.view = view;
        return this;
    }

    /**
     * 显示Toast窗口
     * */
    public void show(){
        if(view == null){
            throw  new RuntimeException("setView must have been called");
        }
        mWindowManager.addView(view,params);
        handler.sendEmptyMessage(SHOW);
    }

    /**
     * 隐藏Toast窗口
     * */
    public void hide() {
        mWindowManager.removeView(view);
    }
}
